package com.xtpt.disaster.controller;

import com.xtpt.disaster.bean.ActionParameters;
import com.xtpt.disaster.bean.TaskInfo;
import com.xtpt.disaster.common.PortalResult;
import com.xtpt.disaster.common.PropertyConfig;
import com.xtpt.disaster.common.consts.DataTypeEnum;
import com.xtpt.disaster.common.consts.TaskTypeEnum;
import com.xtpt.disaster.controller.VO.TaskInfoVO;
import com.xtpt.disaster.service.NodeInfoManageService;
import com.xtpt.disaster.service.TaskInfoManageService;
import com.xtpt.disaster.utils.IDGenerator;
import com.xtpt.disaster.utils.ParseFileAbsolutePath;
import com.xtpt.disaster.utils.QuartzSendBack;
import com.xtpt.disaster.utils.ServerPathUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

@RestController
@CrossOrigin
@Api(tags = "task_info任务信息增删改查接口")
@RequestMapping(value = "/manage/taskinfo")
public class TaskInfoManageController {
    @Autowired
    TaskInfoManageService taskInfoManageService;

    @Autowired
    NodeInfoManageService nodeInfoManageService;

    @Autowired
    ServerPathUtil serverPathUtil;

    @Autowired
    PropertyConfig config;

    @Autowired
    ParseFileAbsolutePath parseFileAbsolutePath;

    @Autowired
    QuartzSendBack quartzSendBack;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskName", value = "任务名称", type = "String"),
            @ApiImplicitParam(name = "taskDesc", value = "任务描述", type = "String"),
            @ApiImplicitParam(name = "taskStarttime", value = "周期任务开始时间", type = "String"),
            @ApiImplicitParam(name = "taskEndtime", value = "周期任务结束时间, 即时任务和定时任务不需要展示也不需要传值，周期任务需要展示，选择一个日期或者无限，表示一直按周期备份，没有停止时间", type = "String"),
            @ApiImplicitParam(name = "taskStatus", value = "任务状态, 暂时不填写", type = "Integer"),
            @ApiImplicitParam(name = "taskType", value = "任务类型，", type = "Integer"),
            @ApiImplicitParam(name = "taskBackupType", value = "任务备份类型，全量0还是增量1", type = "Integer"),
            @ApiImplicitParam(name = "taskFileType", value = "文件类型，数据库0，文件1，虚拟镜像2", type = "Integer"),
            @ApiImplicitParam(name = "taskExecType", value = "任务执行类型， 立刻执行任务 0 在指定时间执行一次 1 日、周、月、年周期性执行", type = "Integer"),
            @ApiImplicitParam(name = "taskUnit", value = "周期单位, 日 0 周 1 月 2 年 3", type = "Integer"),
            @ApiImplicitParam(name = "taskUnitCount", value = "周期间隔 周期备份的间隔时间", type = "Integer"),
            @ApiImplicitParam(name = "dbId", value = "数据库id", type = "Integer"),
            @ApiImplicitParam(name = "nodeId", value = "节点id(数据库不需要此参数，文件备份时需要)", type = "Integer"),
            @ApiImplicitParam(name = "taskClientPath", value = "备份文件路径(数据库备份不需要此参数，文件备份时需要)", type = "String"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", type = "Date"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间", type = "Date"),
    })
    @ApiOperation(value = "保存提交任务信息，并根据任务信息发起定时或周期以及即时任务")
    @PostMapping(value = "/insert")
    public PortalResult insertTaskInfo(@RequestBody TaskInfoVO taskInfo) {
        /**
         * 获取客户端文件的本地路径，并提取出文件名（带后缀）
         */
        Long taskId = IDGenerator.longid();
        taskInfo.setTaskId(taskId);
        String clientFilePath = taskInfo.getTaskClientPath();
        Long clientId = taskInfo.getNodeId();
        String filename = parseFileAbsolutePath.parseFilePath(clientFilePath, clientId);
        /**
         *
         */
        String taskUrl = "http://" + config.getServerIp() + ":" + config.getServerPort();
        String dir = serverPathUtil.getFileServerPath(taskId.toString(), filename);
        String path = dir + "_" + filename;

        if (taskInfo.getTaskFileType().equals(DataTypeEnum.DATABASE.getValue())) {
            if (taskInfo.getTaskType().equals(TaskTypeEnum.BACKUP.getValue())) {
                taskUrl += "/rest/backup";
            } else if (taskInfo.getTaskType().equals(TaskTypeEnum.RECOVER.getValue())) {
                taskUrl += "/rest/recover";
            }
        }
        else if (taskInfo.getTaskFileType().equals(DataTypeEnum.FILE.getValue()) || taskInfo.getTaskFileType().equals(DataTypeEnum.VIRTUAL.getValue())) {
            taskUrl += "/filebackup/backup";
        }
        else
            return PortalResult.error("不支持的数据类型");

        ActionParameters actionParameters = new ActionParameters(taskUrl, "POST", taskInfo);
        PortalResult portalResult = quartzSendBack.taskCallBack(taskInfo, actionParameters);

        if (portalResult.isOK()) {
            PortalResult res = taskInfoManageService.insertTaskInfo(taskInfo);
            if (res.isOK()) {
                portalResult.setMsg("数据库保存任务信息成功！任务启动设置成功！");
            }
            else portalResult.error("数据库保存任务信息失败！");
        }
        else {
            portalResult.setMsg("任务启动设置失败！");
        }
        return portalResult;
    }

    @ApiOperation(value = "任务信息删除接口方法")
    @DeleteMapping(value = "/delete")
    public PortalResult deleteById(@RequestParam(value = "id") Long id) {
        int res = taskInfoManageService.deleteById(id);
        if(res == 1) {
            return PortalResult.ok(res);
        }
        else {
            return PortalResult.error("false");
        }
    }

    @ApiOperation(value = "任务信息添加记录接口方法，不会调用quartz调度模块，只是添加一条任务记录")
    @PostMapping(value = "/justinsert")
    public PortalResult justInsert(@RequestBody TaskInfo taskInfo) {
        PortalResult res = taskInfoManageService.insertTaskInfo(taskInfo);
        return res;
    }

    @ApiOperation(value = "任务信息批量删除方法")
    @PostMapping(value = "/batch/delete")
    public PortalResult deleteBatch(@RequestBody long[] ids) {
        int res = taskInfoManageService.deleteBatch(ids);
        if(res == 0) {
            return PortalResult.error("false");
        }
        else {
            return PortalResult.ok(res);
        }
    }

    @ApiOperation(value = "根据id获取任务信息")
    @GetMapping(value = "/getbyid")
    public PortalResult getAllById(@RequestParam(value = "id") Long id) {
        TaskInfo data = taskInfoManageService.selectTaskInfoById(id);
        return PortalResult.ok(data);
    }

    @ApiOperation(value = "获取所有任务信息")
    @GetMapping(value = "/getall")
    public PortalResult getAllTaskInfo() {
        List<TaskInfo> data = taskInfoManageService.getAllTaskInfo();
        return PortalResult.ok(data);
    }

    @ApiOperation(value = "根据ID更新任务信息")
    @PostMapping (value = "/update")
    public PortalResult updateById(@RequestBody TaskInfo taskInfo) throws ParseException {
        int res = taskInfoManageService.updateTaskInfoById(taskInfo);
        if (res == 1) {
            return PortalResult.ok(res);
        }
        else {
            return PortalResult.error("false");
        }
    }

    @ApiOperation(value = "根据TaskInfo任意条件查询任务信息")
    @PostMapping ("/getbycon")
    public PortalResult getByCondition(@RequestBody TaskInfo taskInfo) {
        List<TaskInfo> list = taskInfoManageService.getTaskInfoByExample(taskInfo);
        return PortalResult.ok(list);
    }
}
